//
//  LoginViewController.m
//  Patrol
//
//  Created by 范武 on 13-2-18.
//  Copyright (c) 2013年 FSTI. All rights reserved.
//

#import "LoginViewController.h"
#import "ShakeQueryViewController.h"
#import "PatrolServiceClient.h"
#import "MBProgressHUD.h"
#import "FWAppDelegate.h"
#import "NSString+uitil.h"
#import "IOSAnalysisClient.h"
@interface LoginViewController ()

@end

@implementation LoginViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationController.navigationBarHidden = YES;
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *defaultUserName = [userDefaults objectForKey:@"userName"];
    self.userName.text = defaultUserName;
    NSString *defaultPassword = [userDefaults objectForKey:@"password"];
    self.password.text = defaultPassword;
    UITapGestureRecognizer * tapReco = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(backgroudTap)];
    tapReco.delegate = self;
    [self.view addGestureRecognizer:tapReco];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)doLogin:(id)sender {
    [[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:self forEvent:nil];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    PatrolServiceClient * client = [PatrolServiceClient shareInstance];
    if (client.networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWiFi || client.networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWWAN) {
        if (![self.userName.text isNotBlank]) {
            [UIUtil alertOKWithTitle:@"提示" withMsg:@"请输入账号" withDelegate:nil];
            [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
            return ;
        }
        if (![self.password.text isNotBlank]) {
            [UIUtil alertOKWithTitle:@"提示" withMsg:@"请输入密码" withDelegate:nil];
            [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
            return ;
        }
        [client loginWithUsername:self.userName.text password:self.password.text resultBlock:^(id outJson, NSError *error) {
            if (!outJson && error!=nil) {
                DLog(@"Threre is somethings wrong %@",error.localizedDescription);
                [UIUtil alertOKWithTitle:@"通知" withMsg:@"未能连接到服务器" withDelegate:nil];
                [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
                return ;
            }
            NSDictionary * result = outJson;
            NSInteger result_code = [result[@"result_code"] integerValue];
            
            [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
            
            if (result_code == 1) {
                FWAppDelegate *appDelegate = (FWAppDelegate *)[UIApplication sharedApplication].delegate;
                appDelegate.userName = self.userName.text;
                NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
                [userDefaults setValue:self.userName.text forKey:@"userName"];
                [userDefaults setValue:self.password.text forKey:@"password"];
                [userDefaults synchronize];
                
                //登陆统计
                [[IOSAnalysisClient sharedInstance] afterLogin];
                //正常登录
                ShakeQueryViewController * next = [[ShakeQueryViewController alloc] initWithNibName:@"ShakeQueryViewController" bundle:nil];
                next.title = @"搜索";
                [self.navigationController pushViewController:next animated:YES];
            }else{
                //密码错误及其它
                NSString * result_desc = result[@"result_desc"];
                [UIUtil alertOKWithTitle:@"错误" withMsg:result_desc withDelegate:nil];
            }
        }];
    }else{
        [UIUtil alertOKWithTitle:@"错误" withMsg:@"当前没有连接任何网络" withDelegate:nil];
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        return;
    }
}


- (void)viewDidUnload {
    [self setUserName:nil];
    [self setPassword:nil];
    [super viewDidUnload];
}

- (void)backgroudTap
{
    [[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:self forEvent:nil];
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    return ![touch.view isKindOfClass:[UIButton class]];
}

#pragma mark - textField
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (textField == self.userName) {
        [self.password becomeFirstResponder];
    }else if(textField == self.password){
        [textField resignFirstResponder];
        [self doLogin:nil];
    }
    return YES;
}
@end
